package com.iotboss.wechat.controller.user;

import com.iotboss.common.constant.JwtClaimsConstant;
import com.iotboss.common.core.domain.entity.SysUser;
import com.iotboss.common.pojo.dto.UserLoginDTO;
import com.iotboss.common.pojo.vo.UserLoginVO;
import com.iotboss.common.properties.JwtProperties;
import com.iotboss.common.result.Result;
import com.iotboss.common.utils.JwtUtil;
import com.iotboss.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resources;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Api(tags = "用户相关接口")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired(required=true)
    JwtProperties jwtProperties;
    /**
     * 小程序用户登录
     * @return
     */
    @ApiOperation("小程序用户登录")
    @PostMapping("login")
    public Result login(@ApiParam("小程序提交的授权码")@RequestBody UserLoginDTO userLoginDTO) throws IOException {
        SysUser user  = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getUserId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getUserId())
                .token(token)
                .openid(user.getOpenId())
                .build();

        return Result.success(userLoginVO);
    }
}
